<template>
  <div>
    <p style="font-size: 20px">{{ msg }}</p>
    <!-- 显示进货列表 -->
    <el-table :data="pagedSupply" style="width: 100%">
      <el-table-column prop="new_id" label="编号" width="80"/>
      <el-table-column prop="drug_name" label="药品名称"/>
      <el-table-column prop="manufacturer_name" label="厂商"/>
      <el-table-column prop="supply_date" label="进货日期"/>
      <el-table-column prop="quantity" label="数量"/>
      <el-table-column prop="total_amount" label="总金额"/>
      <el-table-column align="right">
        <!--        delete与edit的实现-->
        <!--        Delete button -->
        <template #default="scope">
          <div style="display: flex;align-items: center;" v-if="haspermission(['admin','manager'])">
            <!-- Edit button with popover -->
            <el-button size="small" type="danger" @click="open_delete(scope.row)">Delete</el-button>
            <el-popover placement="right" :width="320" trigger="click">
              <template #reference>
                <el-button size="small" @click="setValue(scope.row)">Edit</el-button>
              </template>
              <div>
                <form @submit="handleEdit">
                  <p>向后端修改进货信息:</p>
                  <label>名称：</label>
                  <el-input
                      v-model="saleEdit.drug_name"
                      style="width: 240px"
                      show-word-limit
                      type=text
                  />
                  <label>厂商：</label>
                  <el-input
                      v-model="saleEdit.manufacturer_name"
                      maxlength="20"
                      style="width: 240px"
                      show-word-limit
                      type=text
                  />
                  <label>日期：</label>
                  <el-date-picker
                      v-model="saleEdit.supply_date"
                      type="date"
                      placeholder="选择进货日期"
                      style="width: 240px">
                  </el-date-picker>
                  <label>数量：</label>
                  <el-input
                      v-model="saleEdit.quantity"
                      maxlength="20"
                      style="width: 240px"
                      show-word-limit
                      type="number"
                  /><label>金额：</label>
                  <el-input
                      v-model="saleEdit.total_amount"
                      maxlength="20"
                      style="width: 240px"
                      show-word-limit
                      type="number"
                  />
                  <div style="margin: 20px 0"/>
                  <el-button type="info" round @click="handleEdit(scope.row)" size="small">提交修改</el-button>
                </form>
              </div>
            </el-popover>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        style="margin-top: 30px"
        layout="prev, pager, next"
        :total="total"
        v-model="currentPage"
        :page-size="pageSize"
        @current-change="handlePageChange"
    />

    <div style="display: flex; align-items: center;">
      <!-- 添加进货的表单 -->
      <form @submit="drugSubmit" ref="addForm">
        <h3>向后端添加进货的表单:</h3>
        <el-input
            v-model="inputSupply.drug_name"
            style="width: 240px"
            maxlength="20"
            placeholder="药品名称"
            show-word-limit
            type=text
        />
        <div style="margin: 5px 0"/>
        <el-input
            v-model="inputSupply.manufacturer_name"
            maxlength="20"
            style="width: 240px"
            placeholder="厂商"
            show-word-limit
            type="text"
        /><div style="margin: 5px 0"/>
        <el-date-picker
            v-model="inputSupply.supply_date"
            type="date"
            placeholder="选择进货日期"
            style="width: 240px">
        </el-date-picker><div style="margin: 5px 0"/>
        <el-input
            v-model="inputSupply.quantity"
            maxlength="20"
            style="width: 240px"
            placeholder="数量"
            show-word-limit
            type="number"
        /><div style="margin: 5px 0"/>
        <el-input
            v-model="inputSupply.total_amount"
            maxlength="20"
            style="width: 240px"
            placeholder="总金额"
            show-word-limit
            type="number"
        />
        <hr>
        <el-button type="success" round @click="drugSubmit">提交</el-button>
      </form>
      <div style="padding: 5%"></div>
      <div>
        <h3>查询进货的表单1</h3>
        <label>进货药品名称：</label>
        <el-input type="text" style="width: 240px"/>
        <div style="margin: 20px 0"/>
        <el-button type="info">按药品名称查找</el-button>
      </div>
      <div style="padding: 5%"></div>
      <div>
        <h3>查询进货的表单2</h3>
        <label>进货日期：</label>
        <el-input type="text" style="width: 240px" />
        <div style="margin: 20px 0"/>
        <el-button type="info" >按日期查找</el-button>
      </div>
      <div style="padding: 5%"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {computed, h, onMounted, ref, watch} from 'vue';
import {getSupply, postSupply, deleteSupply, updateSupply} from '@/api/api'
import {ElMessage, ElMessageBox} from "element-plus";
import {useLoginStore} from "@/stores";

const store = useLoginStore();

function haspermission(allowance: string[]) {
  return allowance.indexOf(store.role) !== -1;
}
const msg = ref('欢迎来到进货管理板块');
// drug_name, manufacturer_name, supply_date, quantity, total_amount
const inputSupply = ref({
  drug_name:"",
  manufacturer_name:"",
  supply_date:new Date(),
  quantity:Number,
  total_amount:Number
});

//增
async function drugSubmit() {
  try {

    inputSupply.value.supply_date.setHours(inputSupply.value.supply_date.getHours() + 8);

    let formattedDate: string;

    if (inputSupply.value && inputSupply.value.supply_date) {
      // 使用 toLocaleString 方法将 Date 对象格式化为字符串
      const options: Intl.DateTimeFormatOptions = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      };
      formattedDate = inputSupply.value.supply_date.toISOString().split('T')[0];
    } else {
      // 处理 inputSale.value.treatment_date 不是 Date 对象的情况
      formattedDate = 'Invalid date'; // 或者其他适当的默认值
    }
    const response = await postSupply(inputSupply.value.drug_name,inputSupply.value.manufacturer_name,formattedDate,inputSupply.value.quantity,inputSupply.value.total_amount);
    console.log(response);
    await loadSupplys();
    // 清空输入字段
    inputSupply.value = {drug_name:"", supply_date:new Date(), manufacturer_name:'', quantity:Number,total_amount:Number};
  } catch (error) {
    console.error('Error submitting drug:', error);
    // 在这里可以添加错误处理的逻辑，比如显示错误信息给进货
  }
}

//删
async function deleteSupplyAndHandleResponse(id: number) {
  try {
    const response = await deleteSupply(id);
    console.log('Supply deleted successfully', response);
    await loadSupplys()
  } catch (error) {
    console.error('Error deleting Supply', error);
  }
}

const open_delete = (obj: any) => {
  ElMessageBox({
    title: 'Message',
    message: h('p', null, [
      h('span', null, '请注意删除操作是不可逆的'),
      h('i', {style: 'color: teal'}, '数据库会同步变化'),
    ]),
    showCancelButton: true,
    confirmButtonText: '确认删除',
    cancelButtonText: '取消删除',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        deleteSupplyAndHandleResponse(obj.id);
        // window.location.reload()
        done();
      } else {
        done();
      }
    },
  }).then((action) => {
    ElMessage({
      type: 'info',
      message: `操作结果: ${action === 'confirm' ? '删除成功' : '已取消删除'}`,
    });
  });
}

//改
const saleEdit = ref({
  drug_name:"",
  supply_date:"",
  manufacturer_name:"",
  quantity:Number,
  total_amount:Number
})

function setValue(obj: any) {
  saleEdit.value.drug_name = obj.drug_name;
  saleEdit.value.manufacturer_name = obj.manufacturer_name;
  saleEdit.value.supply_date = obj.supply_date;
  saleEdit.value.quantity = obj.quantity;
  saleEdit.value.total_amount = obj.total_amount;
}


async function handleEdit(obj: any) {
  try {
    const response = await updateSupply(obj.id, saleEdit.value)
    console.log("Supply edit successfully", response)
    await loadSupplys()
    ElMessage({
      type: 'info',
      message: `操作结果:'修改成功'`,
    });
  } catch (error) {
    console.error(error);
  }
}

//查
const drugs = ref([
  {id: 1, drug_name:"", manufacturer_name:'', supply_date:"", quantity:Number, total_amount:Number, new_id: 0},
  {id: 2, drug_name:"", manufacturer_name:'', supply_date:"", quantity:Number, total_amount:Number, new_id: 0},
])
let currentPage = ref(1)
const pageSize = ref(6)
const total = ref(drugs.value.length) // 计算总记录数

watch(drugs, (newValue) => {
  total.value = newValue.length;
});
const pagedSupply = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;

  return drugs.value.slice(startIndex, endIndex);
});

function handlePageChange(newPage: number) {
  currentPage.value = newPage
}

async function loadSupplys() {
  try {
    const response = await getSupply();
    // 假设 response.data 是一个进货数组
    drugs.value = response.data;
    let new_index = 1;
    for (let oneMoney of drugs.value) {
      oneMoney.new_id = new_index;
      new_index++;
    }
  } catch (error) {
    // 处理错误情况
    console.error('Error loading drugs:', error);
  }
}
onMounted(() => {
  loadSupplys();
});

//特殊查寻

</script>